﻿using System.Collections.Generic;
using System.IO;
using NPOI.SS.UserModel;


namespace HEFramework
{
    internal class DataTableExportor
    {
        private LangOutput langoutput = new();
        private Dictionary<string, SheetTable> SheetTables = new();

        public void PrecessFiles()
        {
            DataTableSettingScriptableObject data = DataTableSettingScriptableObject.Instance;
            
            //创建目录
            Directory.CreateDirectory(data.SaveDataPath);
            Directory.CreateDirectory(data.SaveCodePath);
            Directory.CreateDirectory(data.SaveOutputKeyPath);
            
            // 文件处理
            DataTableLog.PrintLog("path =" + data.DataTablePath);
            string[] files = Directory.GetFiles(data.DataTablePath);
            for (int i = 0; i < files.Length; i++)
            {
                FileInfo fileInfo = new FileInfo(files[i]);

                if (fileInfo.Extension != ".xlsx" || fileInfo.Name.StartsWith(data.IgnoreFileWhenStartWith))
                {
                    //是否是excel,只读取xlsx,|| 是否忽略
                }
                else
                {
                    //开始处理
                    DataTableLog.PrintLog("file =" + files[i]);
                    IWorkbook workBook = XssfUtils.OpenWorkBook(files[i]);
                    if (workBook == null || !ProcessXss(fileInfo.Name, workBook))
                    {
                        DataTableLog.PrintError("处理文件失败,file=" + fileInfo.Name);
                    }

                    workBook?.Close();
                }
            }

            // 多语言导出
            langoutput.Save();
        }

        private bool ProcessXss(string _fileName, IWorkbook _workBook)
        {
            DataTableSettingScriptableObject data = DataTableSettingScriptableObject.Instance;
            bool flag = true;
            for (int i = 0; i < _workBook.NumberOfSheets; i++)
            {
                ISheet sheet = _workBook.GetSheetAt(i);
                string sheetName = sheet.SheetName;

                //忽略掉需要忽略的表格
                if (sheetName.StartsWith(data.IgnoreSheetWhenStartWith))
                {
                    continue;
                }
                
                DataTableLog.PrintLog("  sheet = " + sheetName);
                SheetTable sheetTable;
                if (SheetTables.ContainsKey(sheetName))
                {
                    sheetTable = SheetTables[sheetName];
                    sheetTable.Join(_fileName, sheet);
                }
                else
                {
                    sheetTable = new SheetTable(_fileName, sheet);
                    SheetTables.Add(sheetName, sheetTable);
                }

                sheetTable.SaveData(langoutput);
                sheetTable.SaveCode();
            }

            return flag;
        }
    }
}